package com.idol.web.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className StaticResourceUtil
 * @description 静态资源工具
 * @date 2020/11/20 22:13
 **/
public class StaticResourceUtil {

    /**
     * 获取文件所在位置的绝对路径
     * @param webName
     * @param resourcePath
     * @return
     */
    public static String getFileAbsolutePath(String webName, String resourcePath) {
        String path = StaticResourceUtil.class.getResource("/").getPath();
        path += Const.WEBAPPS_DIR.getVal() + File.separator + webName + File.separator +  resourcePath;
        return path;
    }

    /**
     * 将静态资源输出至浏览器
     * @param staticResourceInputStream
     * @param outputStream
     * @throws IOException
     */
    public static void outPutStaticResource(InputStream staticResourceInputStream, OutputStream outputStream)
            throws IOException {
        int totalLength = 0;
        do {
            totalLength = staticResourceInputStream.available();
        } while (totalLength == 0);

        write(outputStream, ResponseHeaderUtil.getHttpHeader200(totalLength).getBytes("GBK"));

        long written = 0;
        int buffer = 1024;
        byte[] bytes = new byte[buffer];

        do {
            if (written + buffer > totalLength) {
                buffer = (int) (totalLength - written);
                bytes = new byte[buffer];
            }
            staticResourceInputStream.read(bytes);
            write(outputStream, bytes);
            written += buffer;
        } while (written < totalLength);
    }

    public static void write(OutputStream outputStream, byte[] context) throws IOException {
        outputStream.write(context);
        outputStream.flush();
    }
}
